package com.heima.kafka.stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
@Slf4j
public class KafkaStreamHelloListener {

    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder) {
        KStream<String, String> kStream = streamsBuilder.stream("leadnews-topic-input");
        /**
         * 处理消息的value
         */
        kStream.flatMapValues(value -> Arrays.asList(value.split(" ")))
                // 按照value进行聚合处理
                .groupBy((key, value) -> value)
                // 时间窗口 每10s聚合一次
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                // 统计单词的个数
                .count()
                // 转换为kStream对象
                .toStream()
                .map((key, value) -> {
                    System.out.println("key:" + key + ",value:" + value);
                    return new KeyValue<>(key.toString(), value.toString());
                })
                // 发送消息
                .to("leadnews-topic-output");
        return kStream;
    }
}
